package com.csw.mybatisSpringboot.config.IndexInterception;


import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

@Component
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class IndexCheckInterceptor implements Interceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        String osName = System.getProperty("os.name");
        if (!osName.toLowerCase().contains("linux")) {
            System.out.println("当前运行环境不是 Linux。");

            // 获取 StatementHandler
            StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
            // 获取 SQL 语句
            String sql = statementHandler.getBoundSql().getSql();
            // 在这里可以对 SQL 进行分析，判断是否使用了索引
            // 可以通过解析 SQL 语句或者调用数据库的工具来进行判断
            // 如果没有使用索引，可以进行日志记录或者抛出异常等处理

            Connection connection = (Connection) invocation.getArgs()[0];
            Statement explainStatement = connection.createStatement();
            ResultSet resultSet = explainStatement.executeQuery("EXPLAIN " + sql.replace("?", "1"));
            // 解析结果集，判断是否使用了索引
            boolean usesIndex = false;
            while (resultSet.next()) {
                String possibleIndex = resultSet.getString("key");
                if (possibleIndex != null && !possibleIndex.isEmpty()) {
                    usesIndex = true;
                } else {
                    usesIndex = false;
                    break;
                }
            }
            if (!usesIndex) {
                // 没有使用索引，进行日志记录或其他处理
                logger.error("【没有走索引】: {}", sql.replace("?", "1"));
            }
        }
        return invocation.proceed();


    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }
}
